package com.example.bpmervice.service.impl;

import com.example.bpmervice.mapper.BpmLeaveMapper;
import com.example.bpmervice.po.BpmLeave;
import com.example.bpmervice.po.TaskPo;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
@Transactional
public class BpmLeaveServiceImpl {

    private final RuntimeService runtimeService;

    private final TaskService taskService;

    private final RepositoryService repositoryService;

    private final BpmLeaveMapper bpmLeaveMapper;

    private final ProcessEngine processEngine;

    private final HistoryService historyService;

    @PostConstruct
    public void init(){
        // 检查流程是否已部署
        long count = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey("leaveRequest")
                .count();

        if (count == 0) {
            repositoryService.createDeployment()
                    .addClasspathResource("processes/leave.bpmn20.xml")
                    .name("请假流程部署")
                    .deploy();
            System.out.println("流程部署完成");
        }else{
            System.out.println("流程已存在");
        }
    }

    /**
     * 启动请假流程
     */
    public BpmLeave startLeaveProcess(BpmLeave leave) {
        // 保存业务数据
        leave.setCreateTime(new Date());
        bpmLeaveMapper.insert(leave);

        // 设置流程变量
        Map<String, Object> variables = new HashMap<>();
        variables.put("applicant", leave.getApplicant());
        variables.put("manager", leave.getManager());
        variables.put("reason", leave.getReason());
        variables.put("days", leave.getDays());
        variables.put("leaveId", leave.getId());

        // 启动流程实例
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
                "leaveRequest", variables);

        // 更新业务数据
        leave.setProcessInstanceId(processInstance.getId());
        bpmLeaveMapper.updateById( leave);
        return leave;
    }

    /**
     * 获取用户任务列表
     */
    public List<TaskPo> getUserTasks(String userId) {
        try {
            List<Task> tasks =  taskService.createTaskQuery()
                    .taskAssignee(userId)
                    .list();
            return tasks.stream()
                    .map(task -> TaskPo.fromTask(task, runtimeService, repositoryService))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取用户任务列表失败", e);
            return null;
        }
    }

    public TaskPo getTaskById(String taskId) {
        Task task = taskService.createTaskQuery()
                .taskId(taskId)
                .singleResult();

        if (task == null) {
            throw new RuntimeException("Task not found: " + taskId);
        }

        return TaskPo.fromTask(task, runtimeService, repositoryService);
    }


    public List<HistoricTaskInstance> getTaskHistory() {
        List<HistoricTaskInstance> tasks = historyService.createHistoricTaskInstanceQuery().list();
        return tasks;
    }

    public List<HistoricActivityInstance> getFinishInstanceHistory(String processInstanceId) {
        List<HistoricActivityInstance> tasks = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).finished().orderByHistoricActivityInstanceEndTime().asc().list();
        return tasks;
    }

    /**
     * 完成任务
     */
    public void completeTask(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }

    /**
     * 部署流程定义
     */
    public void deployProcess() {
        repositoryService.createDeployment()
                .addClasspathResource("processes/leave.bpmn20.xml")
                .deploy();
    }
}
